package org.zecontech.plantvszombie.init;

import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import org.zecontech.plantvszombie.PlantVsZombieMod;
import org.zecontech.plantvszombie.item.KelongItem;
import org.zecontech.plantvszombie.item.PacketItem;

import java.util.function.Function;

public class ModItems {

    public static final Item SUN_ITEM = registerSimpleItem("sun_item");
    public static final Item KELONG = register("kelong", KelongItem::new, new Item.Properties());
    public static final Item SUN_FLOWER_PACKET = registerPacketItem("sun_flower_packet",
            ModEntities.SUN_FLOWER, 50);
    public static final Item CHERRY_BOMB_PACKET = registerPacketItem("cherry_bomb_packet",
            ModEntities.CHERRY_BOMB, 150);

    public static Item registerPacketItem(String name, EntityType<? extends Mob> entityType, int sunAmount) {
        return register(name, properties -> new PacketItem(entityType, properties, sunAmount), new Item.Properties());
    }

    public static Item registerSimpleItem(String name) {
        return register(name, Item::new, new Item.Properties());
    }

    public static Item register(String name, Function<Item.Properties, Item> itemFactory, Item.Properties settings) {
        // 创建资源键
        ResourceKey<Item> itemKey = ResourceKey.create(Registries.ITEM, ResourceLocation.fromNamespaceAndPath(PlantVsZombieMod.MOD_ID, name));

        // 创建物品实例
        Item item = itemFactory.apply(settings.setId(itemKey));

        // 注册物品
        Registry.register(BuiltInRegistries.ITEM, itemKey, item);

        return item;
    }

    public static void register() {
        Registry.register(BuiltInRegistries.CREATIVE_MODE_TAB, "plant-vs-zombie",
                FabricItemGroup.builder()
                .icon(() -> new ItemStack(ModItems.SUN_FLOWER_PACKET))
                .title(Component.translatable("itemGroup.plant-vs-zombie"))
                .displayItems((itemDisplayParameters, output) -> {
                    BuiltInRegistries.ITEM.forEach(item -> {
                        if (BuiltInRegistries.ITEM.getKey(item).getNamespace().equals(PlantVsZombieMod.MOD_ID)) {
                            output.accept(item);
                        }
                    });
                })
                .build());
        PlantVsZombieMod.LOGGER.info("Registered items for " + PlantVsZombieMod.MOD_ID);
    }
}
